package com.hdmall.business.common.util;

import org.icepdf.core.exceptions.PDFException;
import org.icepdf.core.exceptions.PDFSecurityException;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;

public class IcepdfUtil {
    public static void main(String[] args) {
       String s="img/aaa.pdf";
        s=s.substring(0,s.lastIndexOf(".")+1)+"jpg";
        //pdf2Img("pdf/测试公司4-1528346516405.pdf",);
    }
    public static String pdf2Img(String pdfPath,String imgName){
        //String filePath = "pdf/测试公司4-1528346516405.pdf";
        Document document = new Document();

        try {
            document.setFile(pdfPath);
            float scale = 3.2f;// 缩放比例（大图）
            // float scale = 0.2f;// 缩放比例（小图）
            float rotation = 0f;// 旋转角度
            for (int i = 0; i < document.getNumberOfPages(); i++) {
                BufferedImage image = (BufferedImage) document.getPageImage(i,
                        GraphicsRenderingHints.SCREEN,
                        org.icepdf.core.pobjects.Page.BOUNDARY_CROPBOX,
                        //org.icepdf.core.pobjects.Page.BOUNDARY_ARTBOX,
                        rotation, scale);
                RenderedImage rendImage = image;
                try {
                    File file = new File("img/"+imgName);
                    // 这里png作用是：格式是jpg但有png清晰度
                    ImageIO.write(rendImage, "png", file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.flush();
            }
            document.dispose();
        } catch (PDFException e1) {
            e1.printStackTrace();
        } catch (PDFSecurityException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("======================转换完成============================");

        return "img/"+imgName;
    }
}
